<template>
  <div>
    <el-card style="max-width: 80%; margin: 0 auto">
      <el-form
        ref="updateRuleFormRef"
        style="max-width: 70%; margin: 0 auto"
        :model="updateRuleForm"
        label-width="150px"
        class="demo-ruleForm"
        status-icon
        @submit.prevent="submitCreateForm(updateRuleFormRef)"
      >
        <div v-for="item in tableData" :key="item.field">
          <el-form-item
            :label="item.label"
            v-if="item.display === true"
            :prop="
              Object.keys(updateRuleForm).find(
                (key) => updateRuleForm[key] === updateRuleForm[item.field]
              )
            "
            :name="updateRuleForm[item.field]"
            :rules="getValidationRules(item.field)"
          >
            <InputComponent
              v-if="item.dataType === 1"
              v-model="updateRuleForm[item.field]"
              :inputType="'text'"
              @handleInput="handleInput"
              @blur="handleBlur(item.field)"
              @focus="handleFocus(item.field)"
            />
            <InputComponent
              v-if="item.dataType === 4"
              v-model="updateRuleForm[item.field]"
              :inputType="'textarea'"
              :resize="'vertical'"
            />
            <InputComponent
              v-if="item.dataType === 2"
              v-model="updateRuleForm[item.field]"
              :inputType="'number'"
            />
            <SelectComponent
              v-if="item.dataType === 6"
              v-model="updateRuleForm[item.field]"
              :options="typeList"
              @change="onSelectChange"
            />
            <RadioGroupComponent
              v-if="item.dataType === 8"
              v-model="updateRuleForm[item.field]"
              :options="[
                { value: '1', label: '是' },
                { value: '0', label: '否' }
              ]"
            />
            <CheckboxGroupComponent
              v-if="item.dataType === 7"
              v-model="updateRuleForm[item.field]"
              :options="[
                { value: '0', label: '普通会员' },
                { value: '1', label: 'vip' },
                { value: '2', label: 'cms后台管理员' }
              ]"
              @change="onCheckboxChange"
            />
            <DatePickerComponent
              v-if="item.dataType === 5"
              v-model="updateRuleForm[item.field]"
              placeholder="请选择日期和时间"
              @change="handleDateChange"
              valueFormat="YYYY-MM-DD hh:mm:ss"
            />
            <UploadComponent
              v-if="item.dataType === 11"
              v-model="updateRuleForm[item.field]"
              @update:modelValue="uploadFile"
              :limit="10"
            />
            <CascaderComponent
              style="width: 350px"
              v-if="item.dataType === 10"
              v-model="updateRuleForm[item.field]"
              :options="treeData"
              @change="onCascaderChange"
              :cascaderProps="cascaderProps"
              :showAllLevels="true"
            />
            <Editor
              style="width:100%"
              v-if="item.dataType === 9"
              v-model="updateRuleForm[item.field]"
              :readOnlyFlag="readOnly"
              @uploadImage="handleUploadImage"
              @update="handleContentUpdate"
            />
          </el-form-item>
        </div>
      </el-form>
      <div style="text-align: center">
        <div class="dialog-footer">
          <el-button
            type="primary"
            @click="submitCreateForm(updateRuleFormRef)"
          >
            提 交
          </el-button>
          <el-button type="primary" @click="onClose"> 关闭 </el-button>
          <el-button @click="resetUpdateForm(updateRuleFormRef)"
            >重 置</el-button
          >
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue'
import { useStore } from 'vuex'
import InputComponent from '@/views/components/elInput.vue'
import SelectComponent from '@/views/components/elSelect.vue'
import RadioGroupComponent from '@/views/components/elRadio.vue'
import CheckboxGroupComponent from '@/views/components/elCheckboxGroup.vue'
import DatePickerComponent from '@/views/components/elDatePicker.vue'
import CascaderComponent from '@/views/components/elCascader.vue'
import UploadComponent from '@/views/components/elUpload.vue'
import Editor from '@/components/Editor/index.vue'

import {
  getAddContent,
  saveContent,
  saveSecondContent
} from '@/api/content/addContent.js'
import { gettypeListAble, getContentTree } from '@/api/content/contentList.js'
import { dayjs, ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
const router = useRouter()
const store = useStore()
const updateRuleFormRef = ref()
const userId = store.state.app.user.id
const tableData = ref([])
const typeList = ref([])
// 树
const treeData = ref([])
const cascaderProps = {
  children: 'children',
  label: 'name',
  value: 'id',
  checkStrictly: true
}
const updateRuleForm = ref({
  channelId: '',
  title: '',
  typeId: null,
  description: null,
  releaseDate: null,
  multipartFiles: [],
  txt: '',
  user_id: null
})

const handleContentUpdate = (content) => {
  updateRuleForm.value.txt = content
}
const handleUploadImage = () => {
  console.log(123)
}
const updateRules = reactive({
  channelId: [{ required: true, message: '请选择栏目', trigger: 'blur' }],
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  releaseDate: [{ required: true, message: '请选择发布时间', trigger: 'blur' }],
  typeId: [{ required: true, message: '请选择内容类型', trigger: 'blur' }]
})

onMounted(() => {
  getDynamicComponent()
  getTypeListFn()
  getTreeList()
})
const getDynamicComponent = async () => {
  await getAddContent({
    cid: null,
    user_id: 1
  })
    .then((res) => {
      tableData.value = res.data
    })
    .catch((err) => {
      console.log(err)
    })
}
const getTypeListFn = async () => {
  await gettypeListAble()
    .then((res) => {
      if (res.data) {
        res.data.map((item) => {
          typeList.value.push({ label: item.name, value: item.id })
        })
      }
    })
    .catch((err) => {
      console.log(err)
    })
}
const getTreeList = () => {
  const params = { root: 'source', userId: userId }
  getContentTree({ root: params.root, userId: params.userId }).then((res) => {
    const transArr = res.data.resultlist.map((item) => {
      return {
        id: item.id,
        name: `${item.name}`,
        children: item.children
      }
    })
    treeData.value = transArr
  })
}
// 关闭按钮
const onClose = () => {
  router.push({ path: 'ContentManagementList' })
}
// 获取校验规则的方法
const getValidationRules = (name) => {
  return updateRules[name] || []
}

// 弹窗提交
const submitCreateForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      const formData = new FormData()
      const channelId = ref()
      if (updateRuleForm.value.channelId.length > 0) {
        // 获取最后一个选中值
        const lastValue =
          updateRuleForm.value.channelId[
            updateRuleForm.value.channelId.length - 1
          ]
        channelId.value = lastValue
      }
      formData.append('channelId', channelId.value)
      formData.append('typeId', updateRuleForm.value.typeId)
      // formData.append('description', updateRuleForm.value.description)
      // formData.append('title', updateRuleForm.value.title)
      formData.append(
        'releaseDate',
        dayjs(updateRuleForm.value.releaseDate).format('YYYY-MM-DD HH:mm:ss')
      )
      console.log(updateRuleForm.value.multipartFiles)
      updateRuleForm.value.multipartFiles.forEach((file) => {
        if (file.raw) {
          formData.append('multipartFiles', file.raw)
        }
      })
      formData.append('text', updateRuleForm.value.txt)
      formData.append('user_id', userId + '')
      console.log(formData)
      await saveContent(formData)
        .then((res) => {
          saveSecondContent({
            description: updateRuleForm.value.description,
            title: updateRuleForm.value.title,
            content_id: res.data,
            userId
          })
            .then((response) => {
              ElMessage.success(response.message)
              formEl.resetFields()
              updateRuleForm.value = {
                channelId: '',
                title: '',
                typeId: 1,
                description: null,
                releaseDate: null,
                multipartFiles: [],
                txt: '',
                user_id: null
              }
              router.push({ path: 'ContentManagementList' })
            })
            .catch((err) => {
              console.log(err)
            })
        })
        .catch((err) => {
          console.log(err)
        })
    } else {
      console.log('error submit!', fields)
    }
  })
}

// 弹窗重置
const resetUpdateForm = (formEl) => {
  updateRuleForm.value = {
    channelId: '',
    title: '',
    typeId: 1,
    description: null,
    releaseDate: null,
    multipartFiles: [],
    txt: '',
    user_id: null
  }
  formEl.resetFields()
}

const handleInput = () => {
  console.log(123)
}
const uploadFile = (fileList) => {
  updateRuleForm.value.multipartFiles = fileList
}

const onSelectChange = (value) => {
  console.log('选择改变，当前值：', value)
}

// 处理失去焦点事件
const handleBlur = (field) => {
  console.log(`${field} 输入框失去焦点`)
}

// 处理获取焦点事件
const handleFocus = (field) => {
  console.log(`${field} 输入框获取焦点`)
}
// 处理复选框值改变的事件
const onCheckboxChange = (values) => {
  console.log('选中的值改变了:', values)
}
// 处理日期时间选择变化的方法
const handleDateChange = (value) => {
  console.log('选择的日期时间:', value)
}
// 级联选择器方法
const onCascaderChange = (value) => {
  console.log('选中的值:', value)
}
</script>

<style lang="scss" scoped>
::v-deep {
  .el-form {
    .el-form-item {
      .el-form-item__label {
        font-weight: bold !important;
      }
    }
  }
}
</style>
